package com.slf.engine.bo;


import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.springframework.web.context.WebApplicationContext;

import com.slf.engine.common.SysContants;
import com.slf.engine.common.SysContext;
import com.slf.engine.services.IHfzcService;
import com.slf.engine.services.helper.ServiceHelper;
import com.slf.engine.services.impl.BusServiceImpl;
import com.slf.engine.services.impl.HfzcServiceImpl;
import com.slf.engine.utils.ConnectUtil;

public class WaitBean extends Thread {

	private static final Logger log = Logger.getLogger(WaitBean.class);
	
	private WebApplicationContext context;
	
	public WebApplicationContext getContext() {
		return context;
	}
	public void setContext(WebApplicationContext context) {
		this.context = context;
	}
	private Order order;
	public Order getOrder() {
		return order;
	}
	public void setOrder(Order order) {
		this.order = order;
	}
	public long getTimeout() {
		return timeout;
	}
	public void setTimeout(long timeout) {
		this.timeout = timeout;
	}
	public Boolean getIsStart() {
		return isStart;
	}
	public void setIsStart(Boolean isStart) {
		this.isStart = isStart;
	}
	private long timeout;
	private Boolean isStart = true;
	
	public boolean removeFromList()
	{
		synchronized (this) {
			this.setIsStart(false);
			synchronized (SysContext.QUERY_MAP) {
				if(SysContext.QUERY_MAP.containsKey(order.getOrderId()))
				{
					SysContext.QUERY_MAP.remove(order.getOrderId());
					if(!SysContext.QUERY_MAP.containsKey(order.getOrderId()))
					{
						//当队列中不存在
						return true;
					}
				}
			}
		}
		return false;
	}
	
	public void run()
	{
		while(getIsStart()){
			if(getIsStart())
			{
				if(this.getTimeout() != 0 && System.currentTimeMillis() - this.getTimeout() >= 1000*20)//
				{
					IHfzcService connService = new HfzcServiceImpl();
					if(removeFromList())
					{
						log.log(Priority.INFO, "充值出现未知错误，发起主动查询");
						this.order = connService.doQuery(order);
						if(order.getClbz() == SysContants.CZ_RUN)
						{
							ServiceHelper.putToCache(order,context);
						}else{
							new BusServiceImpl(context).doBusResult(order);
						}
					}
				}else{
					try {
						log.log(Priority.INFO, order.getOrderId()+"等待通知返回处理");
						Thread.sleep(1000*10);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
					}
				}
			}
		}
		
	}
}
